import { useUserStore } from '@renderer/stores/user'
import router from '.'
import { Parent } from '@renderer/interface/user'
// 引入路由进度条
// @ts-ignore
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'

// 进度条配置
// nprogress.configure({ showSpinner: false })

export const beforeEach = (to: any) => {
	nprogress.start()

	if (to.path == '/login') {
		return;
	}

	if (!localStorage.getItem('TOKEN')) {
		return '/login'
	}

	//动态添加路由
	initRouter();

	//当前路由没有匹配到任何路由记录
	if (to.matched.length == 0) {
		router.push(to.fullPath);
	}
	return true;
}

interface Child {
	parentView: string;
	path: string;
	name: string;
	meta: any;
	redirect: string;
	children?: Child[] | null;
	component: any;
	id?: string;
	hidden?: boolean;
	alwaysShow?: boolean;
	query?: string;
}

interface Child extends Omit<Parent, 'children'> {
	children?: Child[] | null;
}

//1. 动态添加路由 => 整个过程
const initRouter = () => {
	let menu: Parent[] = useUserStore().menu;

	let menuRouter: Child[] = filterRouter(menu);

	// console.log(menuRouter);

	menuRouter.forEach((item: any) => {
		router.addRoute('layout', item);
	});
}

//2. 把component 重构成箭头函数的形式
const filterRouter = (menu: Parent[]): Child[] => {
	let arrRouter: Child[] = [];
	menu.forEach((item: any) => {
		var route: Child = {
			parentView: item.parentView,
			path: item.path,
			name: item.name,
			meta: item.meta,
			redirect: item.redirect,
			children: item.children ? filterRouter(item.children) : null,
			component: loadComponent(item.component)
		};
		arrRouter.push(route);
	});
	return arrRouter;
};

//3. 对于component的调整
const modules: Record<string, () => Promise<any>> = import.meta.glob('@renderer/views/**/*.vue');
const modulesMap: Record<string, () => Promise<any>> = {};

Object.keys(modules).forEach((key) => {
	const componentName = key.replace('/src/views', '').replace('.vue', '').replace('/index', '').replace('/', '');
	if (key.includes('index')) {
		modulesMap[`${componentName}/index`] = modules[key];
	}
	modulesMap[componentName] = modules[key];
});

//4. 根据modulesMap[key]返回对应的value值
const loadComponent = (component: string | null): (() => Promise<any>) | undefined => {
	if (component) {
		return modulesMap[component];
	}
	return;
};

//后置
export const afterEach = () => {
	nprogress.done()
}